#!/usr/bin/env node
/**
 * Created by renzhiqiang on 18/1/7.
 * !/usr/bin/env node这种用法是为了防止操作系统用户没有将node装在默认的/usr/bin路径里。当系统看到这一行的时候，首先会到env设置里查找node的安装路径，再调用对应路径下的解释器程序完成操作。
 */
'use strict';
var gulp = require('gulp'),
    install = require('gulp-install'),
    conflict = require('gulp-conflict'),
    template = require('gulp-template'),
    inquirer = require('inquirer'),
    fs = require('fs'),
    path = require('path');

    //业务模块生产菜单登录模块
     gulp.task('login', function (done) {
        inquirer.prompt([
            {
                type: 'input',
                name: 'name',
                message: '给项目取个名字',
                default: "" // 从运行参数中获取值作为 name 的默认值。
            },
            {
                type: 'confirm',
                name: 'moveon',
                message: '是否继续?'
            }
        ]).then(function (answers) {
            console.info('111');
            console.info(__dirname + '/templates/app/**');
            gulp.src([__dirname + '/templates/app/**',__dirname + '/templates/app/.*'])  // Note use of __dirname to be relative to generator
                .pipe(template(answers))                 // Lodash template support
                .pipe(conflict('./','a'))                    // Confirms overwrites on file conflicts
                .pipe(gulp.dest('./'))                   // Without __dirname here = relative to cwd
                .on('finish', function () {
                    done();                                // Finished!
                });
        });
    });
     // 导入项目模块
     gulp.task('createProjiect', function (done) {
         inquirer.prompt([
             {
                 type: 'input',
                 name: 'projectName',
                 message: '请输入项目名称',
                 default: "" // 从运行参数中获取值作为 name 的默认值。
             },
         ]).then(function (answers) {
             console.info(answers.projectName)
             gulp.src([__dirname + '/templates/app/**',__dirname + '/templates/app/.*'])  // Note use of __dirname to be relative to generator
                 .pipe(conflict('./','a'))                    // Confirms overwrites on file conflicts
                 .pipe(template({'projectName':answers.projectName}))
                 .pipe(gulp.dest('./'))                   // Without __dirname here = relative to cwd
                 .on('finish', function () {
                     done();                                // Finished!
                 });
         });
        });

     // 导入单点登入项目模块
     gulp.task('createProjiectLogin', function (done) {
         inquirer.prompt([
             {
                 type: 'input',
                 name: 'projectName',
                 message: '请输入项目名称',
                 default: "" // 从运行参数中获取值作为 name 的默认值。
             },
         ]).then(function (answers) {
             gulp.src([__dirname + '/templates/app_v1/**',__dirname + '/templates/app_v1/.*'])  // Note use of __dirname to be relative to generator
                 .pipe(conflict('./','a'))                    // Confirms overwrites on file conflicts
                 // .pipe(template({'projectName':answers.projectName}))
                 .pipe(gulp.dest('./'))                   // Without __dirname here = relative to cwd
                 .on('finish', function () {
                     done();                                // Finished!
                 });
         });
    });

     // 导入parcel项目模块
     gulp.task('createParcel', function (done) {
         gulp.src([__dirname + '/templates/parcel/**',__dirname + '/templates/parcel/.*'])  // Note use of __dirname to be relative to generator
             .pipe(conflict('./','a'))                    // Confirms overwrites on file conflicts
             .pipe(gulp.dest('./'))                   // Without __dirname here = relative to cwd
             .on('finish', function () {
                 done();                                // Finished!
             });
      });


     // 导入静态模块
     gulp.task('allstatic', function (done) {
             inquirer.prompt([
                 {
                     type: 'input',
                     name: 'router',
                     message: '请输入文件夹名称和路由信息',
                     default: "" // 从运行参数中获取值作为 name 的默认值。
                 },
             ]).then(function (answers) {
                 console.info("routes层开始生成");
                 gulp.src([__dirname + '/templates/template/tem/routes/**'])  // Note use of __dirname to be relative to generator
                     .pipe(template({'router':answers.router, 'addRouter':"add"+ucfirst(answers.router)}))                  // Lodash template support
                     .pipe(gulp.dest('./src/routes/'+answers.router));                  // Without __dirname here = relative to cwd
                 console.info("routes层已完成");
                 console.info("models层开始生成");
                 gulp.src([__dirname + '/templates/template/tem/models/**'])  // Note use of __dirname to be relative to generator
                     .pipe(template({'router':answers.router, 'addRouter':"add"+ucfirst(answers.router)}))                  // Lodash template support
                     .pipe(gulp.dest('./src/models/'+answers.router));                      // Without __dirname here = relative to cwd
                 console.info("models层已经完成");
                 console.info("services层开始生成");
                 gulp.src([__dirname + '/templates/template/tem/services/**'])  // Note use of __dirname to be relative to generator
                     .pipe(template({'router':answers.router, 'addRouter':"add"+ucfirst(answers.router)}))
                     .pipe(gulp.dest('./src/services/'+answers.router));                    // Without __dirname here = relative to cwd
                 console.info("services层已经完成");
                 console.info("路由开始构建");
                 addRount(answers.router);
                 console.info("路由构建完毕");
             });
         });
     // 导入动态模块
     gulp.task('alldynamic', function (done) {
         inquirer.prompt([
             {
                 type: 'input',
                 name: 'router',
                 message: '请输入文件夹名称和路由信息',
                 default: "" // 从运行参数中获取值作为 name 的默认值。
             },
         ]).then(function (answers) {
             console.info("routes层开始生成");
             gulp.src([__dirname + '/templates/template/tem_v1/routes/**'])  // Note use of __dirname to be relative to generator
                 .pipe(template({'router':answers.router, 'addRouter':"add"+ucfirst(answers.router)}))                  // Lodash template support
                 .pipe(gulp.dest('./src/routes/'+answers.router));                  // Without __dirname here = relative to cwd
             console.info("routes层已完成");
             console.info("models层开始生成");
             gulp.src([__dirname + '/templates/template/tem_v1/models/**'])  // Note use of __dirname to be relative to generator
                 .pipe(template({'router':answers.router, 'addRouter':"add"+ucfirst(answers.router)}))                  // Lodash template support
                 .pipe(gulp.dest('./src/models/'+answers.router));                      // Without __dirname here = relative to cwd
             console.info("models层已经完成");
             console.info("services层开始生成");
             gulp.src([__dirname + '/templates/template/tem_v1/services/**'])  // Note use of __dirname to be relative to generator
                 .pipe(template({'router':answers.router, 'addRouter':"add"+ucfirst(answers.router)}))
                 .pipe(gulp.dest('./src/services/'+answers.router));                    // Without __dirname here = relative to cwd
             console.info("services层已经完成");
             console.info("路由开始构建");
             addRount(answers.router);
             console.info("路由构建完毕");
         });
});


    // 添加路由
    function addRount(router){
        let newRouter=path.join(process.cwd(), 'src/router.js');
        fs.readFile(newRouter,'utf8', (err, data) => {
            if (err) throw err;
            var newData = data.replace(/(\/\*startRoute\*\/)(.|\n|\r)*(?=\/\*endRoute\*\/)/,function (data) {
                return data + insertRouteNew(router);
            });
            if(newData){
                fs.writeFile(newRouter, newData, (err) => {});
            }
        });
    };
     // 默认执行函数
     gulp.task('default', function (done) {
        inquirer.prompt({type: 'list', name: 'menus', message: '选择操作类型', choices:[{id:'project',name:"导入项目模板"},{id:'business',name:"导入业务模板"}], default: false
                }).then(function (answers) {
                switch (answers.menus){
                    case '导入项目模板' : {
                        inquirer.prompt({
                            type: 'list',
                            name: 'menus',
                            message: '选择项目类型',
                            choices:[
                                {id:'1',name:"导入项目模板"},
                                {id:'2',name:"导入单点登入项目模板"},
                                {id:'3',name:"导入单点登入公共依赖包项目模板"},
                                {id:'4',name:"导入parcel构建项目模板"}
                                ],
                            default: false
                           }).then(function (answers) {
                                switch (answers.menus){
                                    case '导入项目模板' : {
                                        gulp.run("createProjiect");
                                        break;
                                    }
                                    case '导入单点登入项目模板' : {
                                        gulp.run("createProjiectLogin");
                                        break;
                                    }
                                    case '导入单点登入公共依赖包项目模板' : {
                                        console.info("该模板尚未开发,近期开放!");
                                        // gulp.run("createProjiectLogin");
                                        break;
                                    }
                                    case '导入parcel构建项目模板' : {
                                        gulp.run("createParcel");
                                        break;
                                    }
                                }
                        });
                        break;
                    }
                    case '导入业务模板' : {
                        inquirer.prompt({
                            type: 'list',
                            name: 'menus',
                            message: '选择业务模板类型',
                            choices:[{id:'1',name:"静态页面模板"},{id:'2',name:"菜单配置页面模板"},{id:'返回',name:"返回"}],
                            default: false
                        }).then(function (answers) {
                            switch (answers.menus){
                                case '静态页面模板' : {
                                    gulp.run("allstatic");
                                    break;
                                }
                                case '菜单配置页面模板' : {
                                    gulp.run("alldynamic");
                                    break;
                                }
                                case '返回' : {
                                    gulp.run("default");
                                    break;
                                }
                            }
                        });
                        break;
                    }
                }
            });
        });
     // 运行
     gulp.run("default");




    function insertRouteNew(router) {
        return ('{\n' +
        'path: "/'+router+'/:MenuId/:projectId",\n'+
        'name: "'+router+'",\n'+
        'getIndexRoute(nextState, cb) {\n'+
        'require.ensure([], require => {\n'+
                'registerModel(app, require("./models/'+router+'/index"));\n'+
                'registerModel(app, require("./models/'+router+'/add"));\n'+
        'cb(null, {component: require("./routes/'+router+'/index")});\n'+
        '})\n'+
        '}},\n')
    };

    function ucfirst(str) {
        var str = str.toLowerCase();
        str = str.replace(/\b\w+\b/g, function (word) {
            return word.substring(0, 1).toUpperCase() + word.substring(1);
        });
        return str;
    }